<?php
namespace api\modules\v1\models\shop;

use api\modules\v1\models\circle\Circle;
use api\modules\v1\models\Common;
use api\modules\v1\models\user\User;
use common\models\CacheKeys;
use common\models\friend\FriendApply;
use common\models\Functions;
use common\models\shop\Goods;
use common\models\Status;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;


class GoodsComment extends \common\models\shop\GoodsComment
{

    /**
     * 评论圈子
     * @return array
     */
    public function saveComment() {
        $trans = Yii::$app->getDb()->beginTransaction();
        try {
            $userInfo = (new User()) -> checkUser();

            CacheKeys::checkFrequency($userInfo['id'],1);
            $id = (int)Yii::$app->request->post('goods_id','');
            $content = Yii::$app->request->post('content','');
            $replyId = (int)Yii::$app->request->post('reply_id','');

            if (empty($id)) {
                throw new Exception('未知信息');
            }
            $goodsInfo = Goods::getOneByWhere([
                'id' => $id,
                'status' => Status::COMMON_RADIO_YES,
                'is_delete' => Status::COMMON_RADIO_YES,
                'check_status' => Status::COMMON_CHECKING_SUCCESS,
            ]);
            if (empty($goodsInfo)) {
                throw new Exception('未知信息');
            }
            if (empty($content)) {
                throw new Exception('请输入评论内容');
            }

            // 过滤敏感词
            list($isSensitive,$afterStr) = Functions::sensitive($content);
//            if ($isSensitive) {
//                throw new Exception('发布内容不合法！');
//            }

            $data['reply_id'] = 0;
            $data['reply_user_id'] = 0;
            $data['parent_path'] = "0,";
            if ($replyId != 0) {
                $cWhere['id'] = $replyId;
                $cWhere['is_delete'] = Status::COMMON_IS_NOT_DELETE;
                $cInfo = static::getOneByWhere($cWhere);
                if (!$cInfo) {
                    throw new Exception("评论信息不存在");
                }

                # 查询父级信息
                $data['parent_path'] = $cInfo['parent_path'] . $cInfo['id'] . ",";
                if ($userInfo['id'] == $cInfo['user_id']) {
                    throw new Exception("不能回复自己的评论");
                }
                if ($userInfo['id'] != $goodsInfo['user_id']) {
                    throw new Exception("暂时不能回复");
                }

                $data['reply_id'] = $replyId;
                $data['reply_user_id'] = $cInfo['user_id'];
                //评论数量
                static::updateAllCounters(['reply_num' => 1],['id' => $replyId]);
            }

            $data['goods_id'] = $id;
            $data['user_id'] = $userInfo['id'];
            $data['content'] = $content;
            $data['is_delete'] = Status::COMMON_IS_NOT_DELETE;

            $data['status'] = Status::COMMON_CHECKING_SUCCESS;
            if ($isSensitive) {
                $data['status'] = Status::COMMON_CHECKING_WAITING;
            }
            $data['create_time'] = date('Y-m-d H:i:s');

            if (mb_strlen($content,'UTF-8') > 2500) {
                throw new Exception('评论内容超过字数限制');
            }

            $res = static::insertData($data);
            if ($res === false) {
                throw new Exception('评论失败，请稍后尝试');
            }

            if($data['status'] == Status::COMMON_CHECKING_SUCCESS){
                //评论数量
                Goods::updateAllCounters(['comment_nums' => 1],['id' => $id]);

                // 未读数量
                (new FriendApply())->notReadApplyNum($data['topic_user_id']);
                $msg = '评论成功';
            }else{
                $msg = '评论待审核';
            }

            $trans->commit();
            return Functions::formatRestAPI(0, $msg);
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    //评论列表
    public function getCommentList() {
        try {
            $userInfo = (new User()) -> checkUserNoExp();

            $goodsId = (int) Yii::$app->request->get('goods_id','');
            if (empty($goodsId)) {
                throw new Exception('未知参数');
            }
            $goodsInfo = Goods::getOneByWhere([
                'status' => Status::COMMON_RADIO_YES,
                'is_delete' => Status::COMMON_RADIO_YES,
                'check_status' => Status::COMMON_CHECKING_SUCCESS,
                'id' => $goodsId,
            ]);
            if (empty($goodsInfo)) {
                throw new Exception('未知信息');
            }
            $where = $andWhere = [];
            $where['is_delete'] = Status::COMMON_IS_NOT_DELETE;
            $where['status'] = Status::COMMON_CHECKING_SUCCESS;
            $where['goods_id'] = $goodsId;

            $list = static::getObjectByAndWhere($where,$andWhere,'id,goods_id,user_id,content,reply_user_id,reply_id,create_time,reply_num,like_num','id ASC')->with([
                'user' => function ($q) {
                    $q -> select(['id','nick_name','user_face']);
                },
                'replyUser' => function ($q) {
                    $q -> select(['id','nick_name','user_face']);
                },
                'like' => function ($q)  {
                    $q -> select(['*']);
                },

            ])->asArray()->all();

            $userId = $userInfo['id'] ?? 0;

            $result = [];
            foreach ($list as $key => $value) {
                $tmp = [];
                if ($value['reply_id'] == 0) {
                    $tmp = $this->formatData($value,$userId);
                    $tmp['child'] = $this->recursionComment($list,$value['id'],$userId);
                    $result[] = $tmp;
                }

            }

            return Functions::formatRestAPI(0, '',$result);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 递归获取子元素
     * @param array $commentList
     * @param int  $replyId
     * @return array|mixed
     */
    private function recursionComment($commentList = [], $replyId = 0,$userId = 0)
    {

        $return = [];
        foreach ($commentList as $k => $v) {

            if ($v['reply_id'] == $replyId) {
                $return[] = $this->formatData($v,$userId);
            }
        }
        if (!empty($return)) {
            foreach ($return as $k => $v) {

                $children = $this->recursionComment($commentList, $v['id']);

                if (empty($children)) {
                    break;
                }
                if ($v['reply_id'] != $replyId) {
                    foreach ($children as $kk => $vv) {
                        array_push($return,$vv);
                    }
                }
            }
        }
        return $return;
    }

    public function formatData($oneData = [],$userId = 0)
    {
        if (empty($oneData)) {
            return [];
        }
        $singleUserInfo = ArrayHelper::getValue($oneData,'user',[]);
        $singleReplyUserInfo = ArrayHelper::getValue($oneData,'replyUser',[]);
        $singleLikeUserInfo = array_column(ArrayHelper::getValue($oneData,'like',[]),'user_id');

        $data = [
            'id' => (int) $oneData['id'] ?? 0,
            'nick_name' => $singleUserInfo['nick_name'] ?? '已注销',
            'user_id' => $oneData['user_id'] ?? '',
            'user_face' => static::getAvatar($singleUserInfo['user_face']),
            'content' => $oneData['content'],
            'reply_num' => $oneData['reply_num'],
            'reply_id' => $oneData['reply_id'],
            'like_num' => $oneData['like_num'],
            'is_like' => in_array($userId,$singleLikeUserInfo),
            'time' => strtotime($oneData['create_time']),
            'reply_nick_name' => $singleReplyUserInfo['nick_name'] ?? '',
            'reply_user_id' => $singleReplyUserInfo['id'] ?? '',
            'reply_user_face' => $singleReplyUserInfo ? static::getAvatar($singleReplyUserInfo['user_face']) : '',
        ];

        return $data;
    }

    /**
     * 删除评论
     * @param int $id
     * @return array
     */
    public function deleteComment($id = 0) {
        try {
            $userInfo = (new User()) -> checkUser();

            //用户id
            $id = $id ? $id : (int)Yii::$app->request->post('id',0);

            $commentInfo = static::getOneInfoById($id);

            if ( $commentInfo['user_id'] != $userInfo['id']) {
                throw new Exception('无法删除此评论');
            }

            $data['is_delete'] = Status::COMMON_IS_DELETE;
            $data['update_time'] = date('Y-m-d H:i:s');

            $res = static::updateData($data,['id' => $id]);
            if ($res === false) {
                throw new Exception('删除失败，请稍后尝试');
            }

            //评论数量
            Goods::updateAllCounters(['comment_nums' => -1],['id' => $commentInfo['goods_id']]);

            return Functions::formatRestAPI(0, '删除成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 评论和回复我的列表
     * @return array
     */
    public function getCommentMyList()
    {
        try{
            $page = (int) Yii::$app->request->get('page',1);
            $size = (int) Yii::$app->request->get('size',20);

            $user = Yii::$app->getUser()->getIdentity()->toArray();
            if(empty($user)){
                throw new Exception('未知用户');
            }
            $userTx = $user['tx_code'];


            $where = $andWhere = [];
            $andWhere[] = ['or',
                ['reply_user_id' => $user['id']],
                ['topic_user_id' => $user['id']], ['like', "at_user", $userTx]
            ];

            $where['is_delete'] = Status::COMMON_RADIO_NO;

//            $count = static::getCountByAndWhere($where,$andWhere);
//            $data = static::setPageinationAPI($page, $size, $count);

            $data = static::setPaginationForApi($page);
            $offset = ($page - 1) * $size;
            $list = static::getObjectByAndWhere($where, $andWhere, ['*'], 'is_read DESC, id DESC', $offset, $size)
                ->with(['user' => function ($q) {
                    $q -> select(['id','nick_name','tx_code','user_face']);
                },
                    'circle' => function ($q) {
                        $q -> select(['id','title','images']);
                    },
                ])
                ->asArray()->all();

            $result = [];
            $atUserTxCode = [];
            foreach ($list as $v) {
                $singleUserInfo = ArrayHelper::getValue($v,'user',[]);
                $singleCircleInfo = ArrayHelper::getValue($v,'circle',[]);

                $imageTmp = [];
                $imageArray = $singleCircleInfo['images'] ? json_decode($singleCircleInfo['images'],true) : [];
                if ($imageArray) {
                    foreach ($imageArray as $vv) {
                        $imageTmp[] = $this->imageHost . $vv;
                    }
                }

                $tag = "评论了您的动态";
                if ($v['reply_id']) {
                    $tag = "评论了您的评论";
                }

                if ($v['at_user']) {
                    $tag = "在评论@了您";
                }

                $atUserStr = trim($v['at_user']);
                $atUserStr = str_replace("，", ",", $atUserStr);
                $atUserStr = explode(",", $atUserStr);
                $atUserArr = array_unique($atUserStr);
                foreach ($atUserArr as $kk => $vv) {
                    $atUserTxCode[] = $vv;
                }

                $result[] = [
                    'id' => (int) $v['id'],
                    'user_id' => $singleUserInfo['id'] ?: '',
                    'nick_name' => $singleUserInfo['nick_name'] ?? '已注销',
                    'tx_code' => $singleUserInfo['tx_code'] ?? '',
                    'face' => static::getAvatar($singleUserInfo['user_face']),
                    'circle_id' => $singleCircleInfo['id'] ?? '',
                    'title' => $singleCircleInfo['title'] ?? '',
                    'content' => $v['content'],
                    'images' => $imageTmp['0'] ?: '',
                    'like_num' => $v['like_num'],
                    'reply_num' => $v['reply_num'],
                    'time' => strtotime($v['create_time']),
                    'tag' => $tag,
                ];
            }

            # 设为已读
            static::updateData(['is_read' => Status::COMMON_RADIO_YES],['id' => ArrayHelper::getColumn($list,'id')]);

            # @记录表设为已读
            if ($atUserTxCode) {
                CircleCommentAtRelation::updateData(['is_read' => Status::COMMON_RADIO_YES],[
                    'topic_user_id' => $atUserTxCode,
                    'comment_id' => ArrayHelper::getColumn($list,'id'),
                ]);
            }

            // 未读数量
            (new FriendApply())->notReadApplyNum($user['id']);

            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        }catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

}
